const path = require('path');
// 所有的组件名称
const getComponentsName = (str) => {
  const arr = str
    .split('<')
    .filter((s) => s[0] <= 'Z' && s[0] >= 'A')
    .map((s) => {
      const a = s.split('\n')[0];
      const b = a.split('>')[0];
      return b.split(' ')[0];
    });
  return [...new Set(arr)];
};

const getComponentsImport = (components, targetPath) => {
  let ret = '';
  const styledComponents = [];
  const otherComponents = [];
  const yhComponents = [];
  const { componentsDir, basePath } = global.config;
  components.forEach((com) => {
    if (com.slice(0, 2) === 'YH' && !com.includes('.')) yhComponents.push(com);
    else if (com.includes('Styled')) styledComponents.push(com);
    else if (com.slice(0, 2) !== 'YH') otherComponents.push(com);
  });

  // 计算相对路径
  const comsPath = path
    .relative(
      path.join('../', basePath, '/com'),
      path.join('../', `${componentsDir}`)
    )
    .replace(/\\/g, '/');
  console.log('comsPath', comsPath);
  // const comsPath = path.relative(basePath, componentsDir);
  // ret += otherComponents.length
  //   ? `import otherComponents.join(',')}} from '${comsPath}';`
  //   : '';
  otherComponents.forEach((com) => {
    ret += `import ${com} from '${comsPath}/${com}';`;
  });
  if (styledComponents.length) {
    ret += `import {${styledComponents.join(',')}} from './styled'`;
  }

  return {
    ret,
    otherComponents,
    styledComponents,
    yhComponents,
  };
};

module.exports = {
  getComponentsName,
  getComponentsImport,
};
